#!/usr/bin/env python
# -*- coding: utf-8 -*-
from vsphere.models import DeployParam

_RC = [
    # always put on the top
    ('PASS',            'Success'),             # 1000
    ('ERROR',           'General error'),       # 1001
    ('WARNING',         'General warnning'),    # 1002

    # extra error code/message
    ('INVALID_VM_UUID', 'Invalid uuid'),            # 1003
    ('DELETE_VM_ERROR', 'Failed to delete VM'),     # 1004
    ('INVALID_METHOD',  'Invalid request method'),  # 1005
    ('POWEROFF_VM_ERROR', 'Failed to poweroff VM'), # 1006
    ('ACCESS_DENIED',   'Access denied')
]


class ReturnCode(object):
    def __init__(self, rc_set):
        if not isinstance(rc_set, (list, tuple)):
            raise TypeError('Expect list or tuple as input')

        self._rc = {}
        for rc in rc_set:
            self.add(*rc)

    def add(self, key, value):
        key = key.upper()  # prefer upper char as key
        length = len(self._rc)
        self._rc[key] = {}
        self._rc[key]['ID'] = length + 1000
        self._rc[key]['MSG'] = str(value)

    def __getattr__(self, name):
        if hasattr(self._rc, name):
            return getattr(self._rc, name)
        elif name in self._rc.keys():
            return self._rc[name]['ID']
        else:
            raise AttributeError

    def to_message(self, code):
        for v in self._rc.values():
            if v['ID'] == code:
                return v['MSG']

        raise KeyError('No matched return message')


RC = ReturnCode(_RC)


def to_message(code, obj=RC):
    return obj.to_message(code)


class DeployRequest(object):
    def __init__(self, request):
        self.ovaFilePath = request.get('voafilepath')
        self.dataStore = request.get('datastore')
        self.hostName = request.get('hostname')
        self.ipAddress = request.get('ipaddr')
        self.ipList = []
        self.parse_ip_list()

        self.dnsDomain = request.get('dnsdomain')
        self.dnsServer = request.get('dnsserver')
        self.netmask = request.get('netmask')
        self.gateway = request.get('gateway')

        self.adPoolName = "adv_pool" if request.get('adpool') == "" else request.get('adpool')
        self.adStuName = "adv_stu" if request.get('adstu') == "" else request.get('adstu')
        self.msdpPoolName = "msdp_pool" if request.get('msdppool') == "" else request.get('msdppool')
        self.msdpStuName = "msdp_pool" if request.get('msdpstu') == "" else request.get('msdpstu')


    def parse_ip_list(self):
        scope_list = self.ipAddress.split(';')
        for scope in scope_list:
            sublist = scope.split('-')
            size = len(sublist)
            if size == 1:
                self.ipList.append(sublist[0])
            elif size == 2:
                sip = sublist[0].split('.')
                eip = sublist[1].split('.')
                start = int(sip[3])
                stop = int(eip[3])
                if stop >= start:
                    for last in range(start, stop):
                        self.ipList.append(sip[0] + '.' + sip[1] + '.' + sip[2] + '.' + str(last))
            else:
                print("the gaven ip address is wrong")


    def get_deploy_count(self):
        return len(self.ipList)


    def get_deploy_request(self, index):
        deploy_param = DeployParam()
        deploy_param.ovaFilePath = self.ovaFilePath
        deploy_param.dataStore = self.dataStore
        deploy_param.hostName = self.hostName
        deploy_param.ipAddress = self.ipList[index]
        deploy_param.dnsDomain = self.dnsDomain
        deploy_param.dnsServer = self.dnsServer
        deploy_param.netmask = self.netmask
        deploy_param.gateway = self.gateway
        deploy_param.adPoolName = self.adPoolName
        deploy_param.adStuName = self.adStuName
        deploy_param.msdpPoolName = self.msdpPoolName
        deploy_param.msdpStuName = self.msdpStuName


        if self.get_deploy_count() > 1 :
            tail = self.get_ip_string(deploy_param.ipAddress)
            tail_fix = '_' + tail
            if deploy_param.hostName == '' :
                deploy_param.hostName = tail
            else:
                deploy_param.hostName += tail_fix
            deploy_param.adPoolName += tail_fix
            deploy_param.adStuName += tail_fix
            deploy_param.msdpPoolName += tail_fix
            deploy_param.msdpStuName += tail_fix
            
        return deploy_param


    def get_ip_string(self, ip_str):
        ip = ip_str.split('.')
        return "n" + ip[2] + "-h" + ip[3]
